package com.inspur_video.inspur_video.controller;

import com.alibaba.druid.util.StringUtils;
import com.inspur_video.inspur_video.bean.Response;
import com.inspur_video.inspur_video.util.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 图片验证码生成
 */

@RestController
@RequestMapping("/validate_code")
public class ValidateCodeController {
    @Autowired
    HttpSession httpSession;
    /**
     * 获得验证码
     * @param request
     * @param response
     */
    @RequestMapping("/get")
    public void getValidateCode(HttpServletRequest request, HttpServletResponse response) {
        // 先清除之前保存在session中的验证码
        httpSession.removeAttribute("code");
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 告诉浏览器禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 生成验证码
        ValidateCode vCode = new ValidateCode(120, 40, 4, 50);
        // 将以上验证码的正确结果保存到session中以备后续校验
        httpSession.setAttribute("code", vCode.getCode());
        System.out.println(vCode.getCode());
        // 写入到相应输出流中
        try {
            vCode.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 检验验证码是否填写正确
     * @param code
     * @return
     */
    @RequestMapping("/check")
    public Response checkValidateCode(String code) {
        // 从session中获得验证码的正确结果
        String sessionCode = (String) httpSession.getAttribute("code");
        // 移除该结果
        httpSession.removeAttribute("code");
        // 将请求域中的验证码与session中的验证码进行比较
        if (StringUtils.equalsIgnoreCase(code, sessionCode)) {  //忽略验证码大小写
            return new Response(200, "验证成功");
        } else {
            return new Response(500, "验证码错误");
        }
    }
}
